package br.com.afi.web.util;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.servlet.jsp.PageContext;

/**
 * Essa classe possuí método utilitários para os escopos.
 * 
 * @author André de Fontana Ignacio
 * @version 1.0
 */
public class HttpScopeUtil
{
	private PageContext pageContext;
	private HttpServletRequest request;
	private HttpSession session;
	private ServletContext servletContext;

	/**
	 * Construtor
	 * 
	 * @param pageContext Contexto da Página
	 */
	public HttpScopeUtil( PageContext pageContext )
	{
		this.pageContext = pageContext;
		this.request = ( HttpServletRequest ) pageContext.getRequest();
		this.session = request.getSession();
		this.servletContext = session.getServletContext();
	}

	/**
	 * Obtém o atributo em qualquer um dos contextos. Ordem de consulta:<br>
	 * <ol>
	 * <li>pageContext</li>
	 * <li>request</li>
	 * <li>session</li>
	 * <li>servletContext</li>
	 * </ol>
	 * 
	 * @param name Nome do Atributo
	 * @return Atributo
	 */
	public Object getAttribute( String name )
	{
		Object obj = pageContext.getAttribute( name );
		if ( obj == null )
		{
			obj = request.getAttribute( name );
			if ( obj == null )
			{
				obj = session.getAttribute( name );
				if ( obj == null )
				{
					obj = servletContext.getAttribute( name );
				}
			}
		}

		return obj;
	}

	/**
	 * Atribui o atributo ao contexto informado.
	 * 
	 * @param name Nome do Atributo
	 * @param obj Objeto
	 * @param httpScope Escopo
	 */
	public void setAttribute( String name, Object obj, HttpScope httpScope )
	{
		switch ( httpScope )
		{
			case PAGE_CONTEXT:
				pageContext.setAttribute( name, obj );
				break;

			case REQUEST:
				request.setAttribute( name, obj );
				break;

			case SESSION:
				session.setAttribute( name, obj );
				break;

			case SERVLET_CONTEXT:
				servletContext.setAttribute( name, obj );
				break;

		}
	}
}
